<template>  
  <div>  
    <van-nav-bar title="收货地址" left-text="返回" left-arrow @click-left="onClickLeft" />  
    <van-cell-group v-for="ad in addressLists" :key="ad.addId">  
      <van-cell>  
        <van-row font-size="10px" style="color: black;" @click="handleClick(ad)">  
          <van-col>{{ ad.name }}</van-col>  
          <van-col offset="2">{{ ad.phoneNum }}</van-col>  
          <van-col offset="9">  
            <IconFont name="del" @click="handleDelete(ad.addId)"></IconFont>  
          </van-col>  
          <van-col offset="1">  
            <IconFont name="edit" @click="handleEdit(ad.addId)"></IconFont>  
          </van-col>  
        </van-row>  
        <van-row font-size="5">{{ ad.address }}</van-row>  
        <van-row>  
          <van-cell>  
            <button class="rounded-rectangle-button" @click="handleAdd">新增地址</button>  
          </van-cell>  
        </van-row>  
      </van-cell>  

      <van-dialog v-model:show="showEditDialog" title="编辑地址" :before-close="handleEditClose">  
      <van-form  @submit="handleEditSubmit(ad.addId)">  
        <van-field v-model="address.name" label="姓名" :placeholder="ad.name" > </van-field> 
        <van-field v-model="address.phoneNum" label="电话" type="tel" :placeholder="ad.phoneNum"/>  
        <van-field v-model="address.address" label="地址" type="textarea" :placeholder="ad.address"/>  
       
          <van-button native-type="submit" style="color: rgb(0, 4, 255);" >保存</van-button>  
         
      </van-form>  
    </van-dialog>  
    <van-dialog v-model:show="showaddDialog" title="新增地址" :before-close="handleaddClose">  
      <van-form  @submit="addAddress">  
        <van-field v-model="address.name" label="姓名" required > </van-field> 
        <van-field v-model="address.phoneNum" label="电话" type="tel" required/>  
        <van-field v-model="address.address" label="地址" type="textarea" required/>  
       
          <van-button native-type="submit" style="color: rgb(0, 4, 255);" >保存</van-button>  
         
      </van-form>  
    </van-dialog>  
    </van-cell-group>  
    
  </div>  
</template>  
<script setup>
// 返回上一页面
const onClickLeft = () => history.back();
import { ref, reactive, onMounted } from 'vue';
import { showNotify, showToast } from 'vant';
import { default as http, getImageUrl } from '@/utils/request.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter,useRoute } from 'vue-router'; //路由器
const router = useRouter();
const route = useRoute();
const addressLists = reactive([

])
// 获取地址列表  
const getAddressList = () => {
  // console.log("------------" + user.value);
  http.get("/user/info").then((response) => {
    console.log("获取个人信息= ", response);
    console.log("id:", response.data.data.id);
    http.get("/address/list/" + response.data.data.id).then((res) => {
      addressLists.splice(0); //todo 需要将原有的元素清空  
      res.data.data.list.forEach(order => {
        addressLists.push(order);
      });
      console.log('获取地址列表: ', res.data.data.list);
      console.log('addressLists:', addressLists);
      // resolve(); // 当获取待收货列表成功后，返回一个解析成功的Promise  
    }).catch(err => {
      reject(err); // 当请求失败时，返回一个请求失败的Promise  
    });

  }).catch(() => {
  });
};
// 删除地址 
const handleClick = (ad) => {  
      // 处理点击事件，例如显示一个弹窗或跳转到详情页面等  
      console.log('点击了:', ad);  
    };
const handleDelete = (addId) => {  
  console.log('删除:', addId);  
  // 在这里实现删除逻辑，例如从列表中删除条目等  
  ElMessageBox.confirm(`确定要删除此地址吗？`, '提示', {
    type: 'warning'
  }).then(() => {//用户点击确定按钮
    http.delete("/address/" + addId)
      .then((res) => {
        console.log('删除返回值：', res);
        if (res.data.status === 200) {	//修改成功
          ElMessage.success(`删除成功`);
          getAddressList();
        }
      }).catch((err) => {
        console.log('删除失败：', err);
        ElMessage.error(`删除失败`);
      });
  })
    .catch(() => {//点击取消按钮

    });
}; 
//编辑地址
const address = reactive({
  addId:'',
  phoneNum:'',
  name:'',
  address:'',
  userId:''
})
const showEditDialog = ref(false);
let addId = ref('')
const handleEdit = (id) => {  
  addId=id;
  showEditDialog.value = true;  

};
const handleEditSubmit = () => {  
  showEditDialog.value = true;
  // 在这里处理表单提交的逻辑，例如保存数据到后端等
  console.log("在这里处理表单提交的逻辑，例如保存数据到后端等")
  address.addId= addId;
  console.log("addId=",address.addId);
  http.put("/address/info",address)
        .then((res) => {
            const { status, message } = res.data;
            console.log("=========status",status);
            if (200 === status) {
                showNotify({ type: 'success', message: ' 修改成功' });
              
            } else {
                showNotify({ type: 'danger', message });
            }
        }).catch((err) => {
            console.log('失败：', err);
        });
}; 
const handleEditClose = () => {  
  showEditDialog.value = false;  
};  
// 新增地址的方法 
const showaddDialog = ref(false);  
const handleAdd = () => {  
  showaddDialog.value = true;  

};
const handleaddClose = () => {  
  showaddDialog.value = false;  
};  
const addAddress = () => {
  // showaddDialog.value = true; 
  console.log("在这里处理表单提交的逻辑，例如保存数据到后端等");
  http.get("/user/info").then((response) => {
        console.log("获取个人信息= ", response);
        console.log("id:", response.data.data.id);
        address.userId=response.data.data.id;
        http.post("/address",address)
        .then((res) => {
            const { status, message } = res.data;
            console.log("=========status",status);
            if (200 === status) {
                showNotify({ type: 'success', message: ' 添加成功' });
                setTimeout(() => {
                  getAddressList();
                }, 1000);
            } else {
                showNotify({ type: 'danger', message });
            }
        }).catch((err) => {
            console.log('失败：', err);
        });
    }).catch(() => {
    });
  // router.push({path: "/addressedit/"})  
}; 

onMounted(() => {
  getAddressList();
});
</script>
<style>
.rounded-rectangle-button {  
  position: fixed;  
  bottom: 0; /* 将按钮放置在底部 */  
  left: 0; /* 将按钮放置在左侧 */  
  width: 100%; /* 设置按钮宽度为100% */  
  height: 50px; /* 设置按钮高度 */  
  background-color: red; /* 设置红色背景 */  
  border-radius: 20px; /* 设置边框半径为10px，使按钮四个角为圆弧状 */  
  color: black; /* 设置字体颜色为黑色 */  
}  
</style>